import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo, LoginParams } from '@/types/user'
import { loginApi, getUserInfoApi, logoutApi, refreshTokenApi } from '@/api/user'
import { getToken, setToken, removeToken, getRefreshToken, setRefreshToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { getDevPermissions, getDevRolePermissions, logDevPermissions } from '@/utils/permission-dev'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(getToken())
  const userInfo = ref<UserInfo | null>(null)
  const permissions = ref<string[]>([])
  const roles = ref<string[]>([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => userInfo.value?.username || '')  // 修改为与后端一致
  const avatar = computed(() => userInfo.value?.avatar || '')

  // 登录
  const login = async (loginParams: LoginParams) => {
    const response = await loginApi(loginParams)
    const { accessToken, refreshToken, userInfo: loginUserInfo } = response
    
    // 保存tokens
    setToken(accessToken, loginParams.rememberMe)
    setRefreshToken(refreshToken)
    token.value = accessToken
    
    // 设置用户信息
    if (loginUserInfo) {
      userInfo.value = {
        userId: loginUserInfo.userId,
        username: loginUserInfo.username,  // 修改为与后端一致
        nickName: loginUserInfo.nickname,
        email: loginUserInfo.email,
        phoneNumber: loginUserInfo.mobile,
        avatar: loginUserInfo.avatar,
        deptId: loginUserInfo.deptId,
        deptName: loginUserInfo.deptName,
        roles: loginUserInfo.roles,
        permissions: loginUserInfo.permissions,
        postIds: [],
        postNames: [],
        roleIds: [],
        roleNames: [],
        gender: '',
        status: '1',
        createTime: new Date().toISOString()
      }
      permissions.value = loginUserInfo.permissions || []
      roles.value = loginUserInfo.roles || []
    } else {
      // 如果没有在登录响应中返回用户信息，则单独获取
      await getUserInfo()
    }
    
    ElMessage.success('登录成功')
    
    // 跳转到首页或重定向页面
    const redirect = router.currentRoute.value.query.redirect as string
    const defaultRoute = getDefaultRoute()
    router.push(redirect || defaultRoute)
    
    return response
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await getUserInfoApi()
      const data = response
      
      userInfo.value = data.userInfo
      
      // 在开发环境中自动添加权限
      const devPermissions = getDevPermissions()
      const devRoles = getDevRolePermissions()
      
      permissions.value = [
        ...(data.permissions || []),
        ...devPermissions
      ]
      roles.value = [
        ...(data.roles || []),
        ...devRoles
      ]
      
      // 开发环境权限调试
      logDevPermissions()
      
      return data
    } catch (error) {
      // 获取用户信息失败，清除token
      logout()
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await logoutApi()
      }
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error('登出失败:', error)
    } finally {
      // 清除本地数据
      removeToken()
      token.value = ''
      userInfo.value = null
      permissions.value = []
      roles.value = []
      
      // 跳转到登录页
      router.push('/login')
    }
  }

  // 检查认证状态
  const checkAuth = () => {
    if (token.value && !userInfo.value) {
      getUserInfo()
    }
  }

  // 检查权限
  const hasPermission = (permissionList: string[]): boolean => {
    if (!permissionList || permissionList.length === 0) {
      return true
    }
    return permissionList.some(permission => permissions.value.includes(permission))
  }

  // 检查角色
  const hasRole = (roleList: string[]): boolean => {
    if (!roleList || roleList.length === 0) {
      return true
    }
    return roleList.some(role => roles.value.includes(role))
  }

  // 获取默认路由
  const getDefaultRoute = (): string => {
    // 根据用户角色返回不同的默认页面
    if (roles.value.includes('admin')) {
      return '/dashboard'
    } else if (roles.value.includes('user')) {
      return '/profile'
    } else {
      return '/dashboard'
    }
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      const refreshTokenValue = getRefreshToken()
      if (!refreshTokenValue) {
        throw new Error('No refresh token available')
      }
      
      const response = await refreshTokenApi()
      const { accessToken, refreshToken: newRefreshToken } = response
      
      setToken(accessToken)
      if (newRefreshToken) {
        setRefreshToken(newRefreshToken)
      }
      token.value = accessToken
      
      return response
    } catch (error) {
      logout()
      throw error
    }
  }

  // 检查token是否即将过期
  const isTokenExpiring = (): boolean => {
    // 这里可以添加token过期时间检查逻辑
    // 暂时返回false，表示token未过期
    return false
  }

  // 自动刷新token（预留功能）
  // const autoRefreshToken = async () => {
  //   if (isTokenExpiring()) {
  //     try {
  //       await refreshToken()
  //     } catch (error) {
  //       // 刷新失败，静默处理，等待下次请求时处理
  //       console.warn('Token refresh failed:', error)
  //     }
  //   }
  // }

  return {
    // 状态
    token,
    userInfo,
    permissions,
    roles,
    
    // 计算属性
    isLoggedIn,
    userName,
    avatar,
    
    // 方法
    login,
    logout,
    getUserInfo,
    checkAuth,
    hasPermission,
    hasRole,
    refreshToken,
    isTokenExpiring
  }
})
